package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-02-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //课程分类列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        List<OneSubject> finalSubjectList=new ArrayList<>();
        /*
         1.根据条件查询所有的一级分类
         */
        QueryWrapper<EduSubject> queryWrapper=new QueryWrapper();
        queryWrapper.eq("parent_id","0");
        //得到所有的一级分类
        List<EduSubject> oneSubjectList = baseMapper.selectList(queryWrapper);
        /*
          2.查询所有的二级分类
         */
        QueryWrapper<EduSubject> queryWrapper2=new QueryWrapper();
        queryWrapper2.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(queryWrapper2);
        //遍历
        for(EduSubject eduSubject:oneSubjectList){
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject); //将eduSubject中的属性赋值给onesubject，类似与oneSubject.setId(eduSubject.getId)
            finalSubjectList.add(oneSubject);
            //添加二级分类
            List<TwoSubject> twoSubjects=new ArrayList<>();
            for (EduSubject eduSubject2:twoSubjectList) {
                TwoSubject twoSubject=new TwoSubject();
                if(eduSubject2.getParentId().equals(eduSubject.getId())){
                    BeanUtils.copyProperties(eduSubject2,twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
        }
        return finalSubjectList;
    }
}
